package com.readaloud.dao;


import java.io.File;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Properties;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

import com.readaloud.hibernate.user.Author;
import com.readaloud.hibernate.user.Books;
import com.readaloud.hibernate.user.Comment;
import com.readaloud.hibernate.user.Reader;
import com.readaloud.hibernate.user.Users;
import com.readaloud.indexing.Invertedindex;
import com.readaloud.inverted.Registry;


/**
 * JDBC implementation of the ContactDao.  It uses Spring's JDBC stuff
 * to keep things simple.  
 *
 * <p>User: Nick Heudecker</p>
 */
public class InvertedIndexDaoImpl implements InvertedIndexDao {

	private Registry data;
	private Session session;
	
	public void intialize(File dir) {
		Properties conf = new Properties();
		conf.setProperty(Registry.sStopWords, "resources/stopwords-long.txt");
		conf.setProperty(Registry.sDataStorage, "TBD");
		conf.setProperty(Registry.sIndexStorage, "TBD");

		data = new Registry(conf);

		// load test data
		//File dir = new File("D://CMPE226//books//11.txt");
		//File dir = new File("D://CMPE226//books//");
		//File dir2 = new File("C://CMPE226//books//13.txt");
		if(session == null || (!session.isOpen())){
			SessionFactory sessionFactory = createSession();
			session = sessionFactory.openSession();
		}
		
		session.beginTransaction();
		data.register(dir,session);
		//data.register(dir1,session);
		//data.register(dir2,session);
		//session.getTransaction().commit();
		//session.close();

	}

	private SessionFactory createSession(){
			SessionFactory sessionFactory = new Configuration().configure()
					.buildSessionFactory();
		return sessionFactory;
	}
	
	@Override
	public List<Books> query(String query) {
		
		//intialize();
		List<String> words = new ArrayList<String>();
		String[] wordArray = query.split(" ");
		for (String word : wordArray) {
			words.add(word);
		}
		SessionFactory sessionFactory = createSession();
		session = sessionFactory.openSession();
		session.beginTransaction();
		data = new Registry();
		long st = System.nanoTime();
		List<Books> docList = data.query(words,session);
		long et = System.nanoTime();

		System.out.println("---> found " + docList.size() + " documents in " + (et - st) + " ns");
		for (Books d : docList)
			System.out.println(d + "\n");
	
		session.getTransaction().commit();
		session.close();
		
		return docList;
	}

	@Override
	public void saveUser(ArrayList<String> paramList) {
		
		SessionFactory sessionFactory = createSession();
		session = sessionFactory.openSession();
		session.beginTransaction();
		
		if(paramList.get(3) == "Reader")
		{
		Reader reader = new Reader();
		reader.setUserName(paramList.get(0));
		reader.setPassword(paramList.get(1));
		reader.setReaderName(paramList.get(2));
		reader.setUserType("reader");
		//user type saving
				session.save(reader);
		}
		else
		{
		Author author = new Author();
		
		// TODO: remove the hardcoded stuff
		author.setUserName(paramList.get(0));
		author.setPassword(paramList.get(1));
		author.setAuthorName(paramList.get(2));
		author.setUserType("author");
		//user type saving
				session.save(author);
		}
		
		
		session.getTransaction().commit();
		session.close();
		
	}

	@Override
	public Books addComment(Integer userId,String userName, Books book, String commentDescription) {

		SessionFactory sessionFactory = createSession();
		session = sessionFactory.openSession();
		session.beginTransaction();
		
		Comment comment = new Comment();
		comment.setCommentDesc(commentDescription);
		comment.setBooks(book);
		Reader reader = new Reader();
		reader.setUserId(userId);
		reader.setUserName(userName);
		comment.setReader(reader);
		session.save(comment);
		book.getComment().add(comment);
		//book.getComment().add(comment);
		//session.save(book);
		//session.persist(book);
		session.getTransaction().commit();
		session.close();
		return book;
	}

	@Override
	public List<Books> getBooksbyGenre(String inputString, String genre) {

		SessionFactory sessionFactory = createSession();
		session = sessionFactory.openSession();
		session.beginTransaction();
		Query query;
		List<Books> books = new ArrayList<Books>();
		if (inputString != null && "".equals(inputString)) {
			query = session
					.createQuery("from Books b left join b.bookClub bc where bc.genre = '"
							+ genre + "'");
			List<Object> output = query.list();
			Iterator itr = output.iterator();
			while (itr.hasNext()) {
				Object[] object = (Object[]) itr.next();
				for (Object o : object) {
					if (o instanceof Books) {
						books.add((Books) o);
					}
				}
			}
		} else {
			List<String> keywords = new ArrayList<String>();
			String[] wordArray = inputString.split(" ");
			for (String word : wordArray) {
				keywords.add(word);
			}
			data = new Registry();
			books = data.searchByGenre(keywords, session, genre);
		}
		session.close();
		return books;
	}

	@Override
	public List<Books> getBooksbyAgeGroup(String ageGroup) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public List<Books> getBooksbyGenreAndAgeGroup(String genre, String ageGroup) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public Users isValidUser(String userName, String password) {
		SessionFactory sessionFactory = createSession();
		session = sessionFactory.openSession();
		session.beginTransaction();
		Query query = session.createQuery("from Users where userName = '" + userName + "' and password = '" + password + "'");
		List<Users> userList = query.list();
		session.close();
		if(userList.size()>=1){
			return userList.get(0);
		} else {
			return null;
		}
	}

	public Author getAuthorDetails(int authorId) {
		SessionFactory sessionFactory = createSession();
		session = sessionFactory.openSession();
		session.beginTransaction();
		Query query = session
				.createQuery("from Author a left join a.book b where a.userId='" + authorId + "'");
		List<Object> list = query.list();
		session.close();
		List<Books> bookList = new ArrayList<Books>();
		Iterator itr = list.iterator();
		Author author = null;
		if (itr.hasNext()) {
			Object[] pair = (Object[]) itr.next();
			author = (Author) pair[0];
			//bookList = (List)author.getBook();
		}
		return author;
	}

	@Override
	public void updateBiography(int userId, String biography) {
		SessionFactory sessionFactory = createSession();
		session = sessionFactory.openSession();
		session.beginTransaction();
		
		 Author author = (Author)session.get(Author.class, userId);
		 author.setBiography(biography);
		 session.update(author);
		 session.getTransaction().commit();
		 session.close();
	}

	
	
}
